﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ExternalConnections.CApECExcelImportManager
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.ExternalConnections.Res;
using EngineeringInternalExtension;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace DnProcessSimulateCommands.ExternalConnections;

internal class CApECExcelImportManager : CApECExcelManager
{
  internal const string COL_BACKWARD_OPC_SERVER = "OPC Server";
  private CApECExcelImportParams m_params;
  private Dictionary<CApECGeneralUtils.eColumnDataType, int> m_columnTypeToExcelColIndexMap;

  internal CApECExcelImportManager()
  {
  }

  internal bool Import(CApECExcelImportParams importParams, string forceImportPath)
  {
    bool flag = false;
    this.m_params = importParams;
    if (this.Start())
    {
      try
      {
        this.m_params.PrepareDefaultOutput();
        CApECExcelImportManager.FileOpenInfo info;
        flag = this.ShowOpenDialog(forceImportPath, out info);
        if (flag)
        {
          if (info.OpenConfirmed)
          {
            this.m_excelApp.DisplayAlerts = false;
            flag = this.OpenWorkbookAndSheet(info);
            if (flag)
              flag = this.ImportFromSheet();
          }
        }
      }
      catch (COMException ex)
      {
        int errorCode = ex.ErrorCode;
        flag = false;
        this.m_params.ImportResult = CApECExcelImportParams.eImportResult.ExcelFailed;
      }
      finally
      {
        this.Quit();
      }
    }
    else
      this.m_params.ImportResult = CApECExcelImportParams.eImportResult.ExcelFailed;
    return flag;
  }

  private bool OpenWorkbookAndSheet(CApECExcelImportManager.FileOpenInfo openInfo)
  {
    bool flag = false;
    if (this.m_excelApp != null)
    {
      this.m_params.FilePath = openInfo.FilePath;
      // ISSUE: reference to a compiler-generated method
      this.m_workbook = this.m_excelApp.Workbooks.Open(this.m_params.FilePath, Type.Missing, (object) true, (object) 5, (object) "", (object) "", (object) true, (object) XlPlatform.xlWindows, (object) "\t", (object) false, (object) false, (object) 0, (object) true, Type.Missing, Type.Missing);
      if (this.m_workbook != null)
      {
        this.m_sheet = this.m_workbook.Sheets[(object) 1] as Worksheet;
        if (this.m_sheet != null)
          flag = true;
      }
    }
    if (!flag)
      this.m_params.ImportResult = CApECExcelImportParams.eImportResult.ExcelFailed;
    return flag;
  }

  private bool ShowOpenDialog(string forceImportPath, out CApECExcelImportManager.FileOpenInfo info)
  {
    bool flag = false;
    info = (CApECExcelImportManager.FileOpenInfo) null;
    if (this.m_excelApp != null)
    {
      int firstPositiveInt = this.ExtractFirstPositiveInt(this.m_excelApp.Version);
      string empty = string.Empty;
      string str = firstPositiveInt < 12 ? "Microsoft Excel Workbook (*.xls)|*.xls" : "Microsoft Excel Workbook (*.xls;*.xlsx)|*.xls;*.xlsx";
      using (OpenFileDialog openFileDialog = new OpenFileDialog())
      {
        openFileDialog.Title = this.m_params.BrowseDialogTitle;
        openFileDialog.CheckPathExists = true;
        openFileDialog.DefaultExt = "xls";
        openFileDialog.Filter = str;
        openFileDialog.AddExtension = true;
        flag = true;
        info = new CApECExcelImportManager.FileOpenInfo();
        info.OpenConfirmed = forceImportPath != null || openFileDialog.ShowDialog() == DialogResult.OK;
        if (info.OpenConfirmed)
          info.FilePath = forceImportPath == null ? openFileDialog.FileName : forceImportPath;
        else
          this.m_params.ImportResult = CApECExcelImportParams.eImportResult.UserAbort;
      }
    }
    else
    {
      this.m_params.ImportResult = CApECExcelImportParams.eImportResult.ExcelFailed;
      flag = false;
    }
    return flag;
  }

  private bool ImportFromSheet()
  {
    bool flag = this.ProcessHeaders();
    if (flag)
      flag = this.ImportAllData();
    return flag;
  }

  private bool ProcessHeaders()
  {
    bool flag1 = true;
    int count = this.m_params.ColumnTypeToColDataMap.Count;
    Dictionary<CApECGeneralUtils.eColumnDataType, int> dictionary = new Dictionary<CApECGeneralUtils.eColumnDataType, int>(count);
    int num1 = this.m_params.ColumnTypeToColDataMap.Count + 10;
    int row = 1;
    for (int index = 0; index < num1 & flag1; ++index)
    {
      int num2 = index + 1;
      object cellValue = this.GetCellValue(row, index + 1);
      if (cellValue != null && cellValue is string str)
      {
        if (str.Equals("OPC Server", StringComparison.InvariantCultureIgnoreCase))
          str = "Server";
        bool flag2 = false;
        Dictionary<CApECGeneralUtils.eColumnDataType, CApECExcelBaseParams.ColData>.Enumerator enumerator = this.m_params.ColumnTypeToColDataMap.GetEnumerator();
        while (enumerator.MoveNext())
        {
          if (enumerator.Current.Value.Caption.Equals(str, StringComparison.InvariantCultureIgnoreCase))
          {
            if (!dictionary.ContainsKey(enumerator.Current.Key))
            {
              dictionary.Add(enumerator.Current.Key, num2);
              flag2 = true;
              break;
            }
            this.m_params.ImportResult = CApECExcelImportParams.eImportResult.DuplicatedColumnFound;
            this.m_params.Errors.Add(string.Format(CUiECExternalConnectionsResourceTable.LOG_FILE_DUPLICATED_COLUMN, (object) str));
            flag1 = false;
            break;
          }
        }
        if (flag2 && dictionary.Count == count)
          break;
      }
    }
    if (flag1 && dictionary.Count < count)
    {
      List<CApECGeneralUtils.eColumnDataType> eColumnDataTypeList = new List<CApECGeneralUtils.eColumnDataType>();
      eColumnDataTypeList.Add(CApECGeneralUtils.eColumnDataType.Type);
      eColumnDataTypeList.Add(CApECGeneralUtils.eColumnDataType.NameSpaceIndex);
      eColumnDataTypeList.Add(CApECGeneralUtils.eColumnDataType.InstanceName);
      eColumnDataTypeList.Add(CApECGeneralUtils.eColumnDataType.COMElement);
      eColumnDataTypeList.Add(CApECGeneralUtils.eColumnDataType.PluginState);
      eColumnDataTypeList.Add(CApECGeneralUtils.eColumnDataType.TagAccessMode);
      foreach (CApECGeneralUtils.eColumnDataType key in this.m_params.ColumnTypeToColDataMap.Keys)
      {
        if (!eColumnDataTypeList.Contains(key) && !dictionary.ContainsKey(key))
        {
          this.m_params.ImportResult = CApECExcelImportParams.eImportResult.MissingColumnFound;
          this.m_params.Errors.Add(string.Format(CUiECExternalConnectionsResourceTable.LOG_FILE_MISSING_MANDATORY_COLUMN, (object) this.m_params.ColumnTypeToColDataMap[key].Caption));
          flag1 = false;
          break;
        }
      }
    }
    if (flag1)
      this.m_columnTypeToExcelColIndexMap = dictionary;
    return flag1;
  }

  private bool ImportAllData()
  {
    bool flag = true;
    int num1 = 5;
    int num2 = 0;
    int row = 1 + 1;
    while (flag && num2 < num1)
    {
      bool isEmptyRow = true;
      flag = this.ImportData(row, out isEmptyRow);
      if (flag)
      {
        if (isEmptyRow)
          ++num2;
        else
          num2 = 0;
        ++row;
      }
    }
    return flag;
  }

  private bool ImportData(int row, out bool isEmptyRow)
  {
    bool flag = true;
    isEmptyRow = false;
    int num = 0;
    Dictionary<CApECGeneralUtils.eColumnDataType, int>.Enumerator enumerator1 = this.m_columnTypeToExcelColIndexMap.GetEnumerator();
    Dictionary<CApECGeneralUtils.eColumnDataType, object> dictionary1 = new Dictionary<CApECGeneralUtils.eColumnDataType, object>();
    while (enumerator1.MoveNext())
    {
      int row1 = row;
      KeyValuePair<CApECGeneralUtils.eColumnDataType, int> current = enumerator1.Current;
      int column = current.Value;
      object cellValue = this.GetCellValue(row1, column);
      string str1 = cellValue != null ? cellValue.ToString() : string.Empty;
      if (str1.Length == 0)
        ++num;
      Dictionary<CApECGeneralUtils.eColumnDataType, object> dictionary2 = dictionary1;
      current = enumerator1.Current;
      int key = (int) current.Key;
      string str2 = str1;
      dictionary2.Add((CApECGeneralUtils.eColumnDataType) key, (object) str2);
    }
    isEmptyRow = num == this.m_columnTypeToExcelColIndexMap.Count;
    if (!isEmptyRow)
    {
      Dictionary<CApECGeneralUtils.eColumnDataType, object>.Enumerator enumerator2 = dictionary1.GetEnumerator();
      IApECExternalConnectionDataConvertor convertor = this.GetConvertor(enumerator2);
      TxPlcOpcUAConnectionDataEx data = convertor.Data as TxPlcOpcUAConnectionDataEx;
      while (enumerator2.MoveNext())
      {
        CApECGeneralUtils.eColumnDataType key = enumerator2.Current.Key;
        object obj = enumerator2.Current.Value;
        try
        {
          switch (key)
          {
            case CApECGeneralUtils.eColumnDataType.Name:
              convertor.Name = obj;
              continue;
            case CApECGeneralUtils.eColumnDataType.OpcServer:
              convertor.OpcServer = obj;
              continue;
            case CApECGeneralUtils.eColumnDataType.ItemHeader:
              string str = convertor.Type.ToString();
              if (obj.ToString() == "N\\A" && (str == "OPC_UA" || str == "WIN_MOD" || str == "SIMIT" || str == "USER_DEFINED"))
              {
                convertor.ItemHeader = (object) "";
                this.m_params.Warnings.Add(string.Format(CUiECExternalConnectionsResourceTable.OPC_UA_ITEMHEADER, (object) row));
                continue;
              }
              convertor.ItemHeader = obj;
              continue;
            case CApECGeneralUtils.eColumnDataType.NameSpaceIndex:
              convertor.NameSpaceIndex = obj;
              continue;
            case CApECGeneralUtils.eColumnDataType.InstanceName:
              convertor.InstanceName = obj;
              continue;
            case CApECGeneralUtils.eColumnDataType.COMElement:
              convertor.COMElement = obj;
              continue;
            case CApECGeneralUtils.eColumnDataType.MapSignalsBy:
              convertor.MapSignalsBy = obj;
              continue;
            case CApECGeneralUtils.eColumnDataType.PluginState:
              convertor.PluginState = obj;
              continue;
            case CApECGeneralUtils.eColumnDataType.TagAccessMode:
              convertor.TagAccessMode = obj;
              continue;
            default:
              continue;
          }
        }
        catch (ArgumentException ex)
        {
          this.m_params.ImportResult = CApECExcelImportParams.eImportResult.DataMismatch;
          this.m_params.Errors.Add(string.Format(CUiECExternalConnectionsResourceTable.LOG_FILE_DATA_MISMATCH, (object) this.m_params.ColumnTypeToColDataMap[key].Caption, (object) row));
          flag = false;
        }
      }
      if (flag)
        this.m_params.ImportedDataList.Add(convertor.Data);
    }
    return flag;
  }

  private IApECExternalConnectionDataConvertor GetConvertor(
    Dictionary<CApECGeneralUtils.eColumnDataType, object>.Enumerator valuesEnumerator)
  {
    ITxPlcExternalConnectionDataEx data = (ITxPlcExternalConnectionDataEx) null;
    while (valuesEnumerator.MoveNext())
    {
      KeyValuePair<CApECGeneralUtils.eColumnDataType, object> current = valuesEnumerator.Current;
      CApECGeneralUtils.eColumnDataType key = current.Key;
      current = valuesEnumerator.Current;
      string str = (string) current.Value;
      if (key == CApECGeneralUtils.eColumnDataType.Type)
      {
        if (str.Equals(CUiECExternalConnectionsResourceTable.OPC_TYPE, StringComparison.InvariantCultureIgnoreCase) || str.Equals(CUiECExternalConnectionsResourceTable.OPC_DA_TYPE, StringComparison.InvariantCultureIgnoreCase))
          data = (ITxPlcExternalConnectionDataEx) new TxPlcOpcConnectionDataEx();
        else if (str.Equals(CUiECExternalConnectionsResourceTable.OPC_UA_TYPE, StringComparison.InvariantCultureIgnoreCase))
          data = (ITxPlcExternalConnectionDataEx) new TxPlcOpcUAConnectionDataEx();
        else if (str.Equals(CUiECExternalConnectionsResourceTable.SIMBA_PNIO_TYPE, StringComparison.InvariantCultureIgnoreCase) || str.Equals(CUiECExternalConnectionsResourceTable.SIMBA_PNIO_TYPE_DEPRECATED, StringComparison.InvariantCultureIgnoreCase))
          data = (ITxPlcExternalConnectionDataEx) new TxPlcSimbaConnectionDataEx();
        else if (str.Equals(CUiECExternalConnectionsResourceTable.PLCSIM_ADVANCED_TYPE, StringComparison.InvariantCultureIgnoreCase))
          data = (ITxPlcExternalConnectionDataEx) new TxPlcSimAdvConnectionDataEx();
        else if (str.Equals(CUiECExternalConnectionsResourceTable.WIN_MODE_TYPE, StringComparison.InvariantCultureIgnoreCase))
          data = (ITxPlcExternalConnectionDataEx) new TxPlcWinModConnectionDataEx();
        else if (str.Equals(CUiECExternalConnectionsResourceTable.SIMIT_COUPLING_TYPE, StringComparison.InvariantCultureIgnoreCase))
          data = (ITxPlcExternalConnectionDataEx) new TxPlcSimitCouplingConnectionDataEx();
        else if (str.Equals(CUiECExternalConnectionsResourceTable.USER_DEFINED_TYPE, StringComparison.InvariantCultureIgnoreCase))
          data = (ITxPlcExternalConnectionDataEx) new TxPlcUserDefinedConnectionDataEx();
      }
    }
    if (data == null)
      data = (ITxPlcExternalConnectionDataEx) new TxPlcOpcConnectionDataEx();
    return this.m_params.DataConvertor.CreateInstance(data);
  }

  private class FileOpenInfo
  {
    internal bool OpenConfirmed;
    internal string FilePath = string.Empty;
  }
}
